package com.winit.openapi.ums.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.CustomerChangeBodyCommand;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.ums.spi.UmsUserService;
import com.winit.ums.spi.commnad.customer.CustomerActviationCommand;
import com.winit.ums.spi.customer.RegisterTemporaryService;
import com.winit.ums.spi.customer.command.AddPotentialCustomerCommand;
import com.winit.ums.spi.customer.command.ChangeAddressCommand;
import com.winit.ums.spi.customer.command.CheckCustomerNameCommand;
import com.winit.ums.spi.customer.command.CheckIdentityCommand;
import com.winit.ums.spi.customer.command.MailRegisterCommand;
import com.winit.ums.spi.customer.command.ReallySaveCommand;
import com.winit.ums.spi.customer.command.RegisterTemporaryCommand;
import com.winit.ums.spi.customer.command.UpdateElseInfoCommand;
import com.winit.ums.spi.customer.vo.MaterialsTemporaryVo;
import com.winit.ums.spi.customer.vo.MerchandiseCategoriesTepVo;
import com.winit.ums.spi.customer.vo.RegisterTemporaryVo;
import com.winit.ums.spi.customer.vo.SupplyChainTepVo;
import com.winit.ums.spi.customer.vo.SupplyCountryTepVo;
import com.winit.ums.spi.customer.vo.SupplyPeakmonthTepVo;
import com.winit.ums.spi.customer.vo.SupplySlackmonthTepVo;
import com.winit.ums.spi.promote.PromoteService;
import com.winit.ums.spi.promote.command.QueryActivityTypeCommand;
import com.winit.ums.spi.promote.command.UpdatePromoteUrlCommand;
import com.winit.ums.spi.promote.vo.PromoteUrlVo;
import com.winit.ums.spi.vo.user.UserVO;

@Controller
@RequestMapping(value = "/ums/temporarily")
public class TemporarilyController extends BaseController {
	
	@Resource
    private RegisterTemporaryService registerTemporaryService;
	
	@Resource
    private PromoteService  promoteService;
	
	@Resource
	private UmsUserService umsUserService;

	@Resource
	private UmsCustomerService umsCustomerService;
	
	/**
     *  邮箱注册账户
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
	@RequestMapping(value = "/mailRegister")
	public String mailRegister(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
		MailRegisterCommand command = JSON.parseObject(requestMsg.getData().toString(), MailRegisterCommand.class);
		command.setCtx(CommandContext.getContext());
		registerTemporaryService.mailRegister(command);		
		Map<String, String> data = new HashMap<String, String>();
		data.put("email", command.getEmail());
		responseMsg.setData(data);
		return SUCCESS;
	}
	
	/**
     *  账户激活
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
	@RequestMapping(value = "/activeCustomer")
    public String activeCustomer(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
	    CustomerActviationCommand activeCommand = JSON.parseObject(requestMsg.getData().toString(), CustomerActviationCommand.class);
	    activeCommand.setCtx(CommandContext.getContext());
        String email = registerTemporaryService.activeCustomer(activeCommand);
        Map<String, String> data = new HashMap<String, String>();
        data.put("email", email);
        responseMsg.setData(data);
        return SUCCESS;               
    }
	/**
     * 客户注册接口保存到零时表
     * @param requestMsg
     * @param responseMsg
     * @return String
     */
	@RequestMapping(value = "/saveTemporarily")
	public String saveTemporarily(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
		RegisterTemporaryCommand command = JSON.parseObject(requestMsg.getData().toString(), RegisterTemporaryCommand.class);
		command.setCtx(CommandContext.getContext());
		String coustomCode = registerTemporaryService.saveTemporaryData(command);
		Map<String, String> data = new HashMap<String, String>();
        data.put("coustomCode", coustomCode);
        responseMsg.setData(data);
       return SUCCESS;
    }
	
	/**
	 * 将数据插入到正式表里
	 * @param requestMsg
     * @param responseMsg
     * @return String
	 * */
	@RequestMapping(value = "/newUserRegister")
	public String newUserRegister(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
		ReallySaveCommand command = JSON.parseObject(requestMsg.getData().toString(), ReallySaveCommand.class);
		command.setCtx(CommandContext.getContext());
		String coustomCode = registerTemporaryService.newUserRegister(command);
		Map<String, String> data = new HashMap<String, String>();
        data.put("coustomCode", coustomCode);
        responseMsg.setData(data);
		return SUCCESS;
	}
	
	
	/**
	 * 修改客户信息
	 * @param requestMsg
     * @param responseMsg
     * @return String
	 * */
	@RequestMapping(value="/updateElseInfoCommand")
	public String updateElseInfoCommand(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
		UpdateElseInfoCommand command = JSON.parseObject(requestMsg.getData().toString(), UpdateElseInfoCommand.class);
		command.setCtx(CommandContext.getContext());
		String coustomCode = registerTemporaryService.updateElseInfoCommand(command);
		Map<String, String> data = new HashMap<String, String>();
        data.put("coustomCode", coustomCode);
        responseMsg.setData(data);
		return SUCCESS;
	}
	
	@RequestMapping(value="/changeAddress")
	public String changeAddress(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
	    ChangeAddressCommand command = JSON.parseObject(requestMsg.getData().toString(), ChangeAddressCommand.class);
        command.setCtx(CommandContext.getContext());
        String coustomCode = registerTemporaryService.changeAddress(command);
        Map<String, String> data = new HashMap<String, String>();
        data.put("coustomCode", coustomCode);
        responseMsg.setData(data);
        return SUCCESS;
    }
	
	
	
	/**
	 * 注册第二步未完成返回以填写资料
	 * @param requestMsg
     * @param responseMsg
     * @return String
	 * */
	@RequestMapping(value="/queryRegisterTemporary")
	public String queryRegisterTemporary(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
		RegisterTemporaryCommand command = JSON.parseObject(requestMsg.getData().toString(), RegisterTemporaryCommand.class);
		command.setCtx(CommandContext.getContext());
		RegisterTemporaryVo vo = registerTemporaryService.getTemporaryRecord(command);
		if(vo != null){
			Map<String, Object> map = this.bulidRegisterTemporaryVo(vo);
			responseMsg.setData(map);
		}
		return SUCCESS;
	}
	
	/**
	 * 个人转企业 
	 * @param requestMsg
     * @param responseMsg
     * @return String
	 * */
	@RequestMapping(value="/personalBecomeEnterprise")
	public String personalBecomeEnterprise(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
		UpdateElseInfoCommand command = JSON.parseObject(requestMsg.getData().toString(), UpdateElseInfoCommand.class);
		command.setCtx(CommandContext.getContext());
		String coustomCode = registerTemporaryService.personalBecomeEnterprise(command);
		Map<String, String> data = new HashMap<String, String>();
        data.put("coustomCode", coustomCode);
        responseMsg.setData(data);
		return SUCCESS;
	}
	
	private Map<String, Object> bulidRegisterTemporaryVo(RegisterTemporaryVo vo){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", vo.getId());
		map.put("email", vo.getEmail());
		map.put("customerType", vo.getCustomerType());
		map.put("type", vo.getType());
		map.put("name", vo.getName());
		map.put("phone", vo.getPhone());
		map.put("country", vo.getCountry());
		map.put("countryCode", vo.getCountryCode());
		map.put("state", vo.getState());
		map.put("stateCode", vo.getStateCode());
		map.put("city", vo.getCity());
		map.put("cityCode", vo.getCityCode());
		map.put("district", vo.getDistrict());
		map.put("districtCode", vo.getDistrictCode());
		map.put("address", vo.getAddress());
		map.put("averageIncome", vo.getAverageIncome());
		map.put("productType", vo.getProductType());
		map.put("development", vo.getDevelopment());
		map.put("contactName", vo.getContactName());
		map.put("contactJobTitle", vo.getContactJobTitle());
		map.put("contactJobDes", vo.getContactJobDes());
		map.put("contactWechat", vo.getContactWechat());
		map.put("contactQq", vo.getContactQq());
		map.put("emergencyContact", vo.getEmergencyContact());
		map.put("emergencyContactPhone", vo.getEmergencyContactPhone());
		map.put("recommenderEmail", vo.getRecommenderEmail());
		map.put("recommendUser", vo.getRecommendUser());
		map.put("tel", vo.getTel());
		map.put("legalName", vo.getLegalName());
		map.put("companySize", vo.getCompanySize());
		map.put("tradingReason", vo.getTradingReason());
		map.put("haveBrand", vo.getHaveBrand());
		map.put("ebayId", vo.getEbayId());
		map.put("ebayBu", vo.getEbayBu());
		map.put("ebayAm", vo.getEbayAm());
		map.put("contactsModifier", vo.getContactsModifier());
		map.put("faxNumber", vo.getFaxNumber());
		map.put("supplayFactoryAddress", vo.getSupplayFactoryAddress());
		map.put("businessLicenseNo", vo.getBusinessLicenseNo());
		map.put("businessCertificateNo", vo.getBusinessCertificateNo());
		map.put("idCardNo", vo.getIdCardNo());
		map.put("isHaveItsystem", vo.getIsHaveItsystem());
		map.put("isHaveErp", vo.getIsHaveErp());
		map.put("potentialCode", vo.getPotentialCode());
		//资料列表
		List<Map<String, Object>> materialsMaps = new ArrayList<Map<String, Object>>();
		List<MaterialsTemporaryVo> materialsList = vo.getMaterialsTemporary();
		if(materialsList != null && materialsList.size() > 0){
			for (MaterialsTemporaryVo materials : materialsList) {
				Map<String, Object> materialsMap = new HashMap<String, Object>();
				materialsMap.put("type", materials.getType());
				materialsMap.put("number", materials.getNumber());
				materialsMap.put("image1", materials.getImage1());
				materialsMap.put("image2", materials.getImage2());
				materialsMap.put("image3", materials.getImage3());
				materialsMaps.add(materialsMap);
			}
		}
		map.put("materialsTemporary", materialsMaps);
		
		//供应链
        Map<String, Object> chainMap = new HashMap<String, Object>();
        SupplyChainTepVo chainVos = vo.getSupplyChainTep();
        if(chainVos!=null){
            chainMap.put("supplayAgentorprivat", chainVos.getSupplayAgentorprivat());
            chainMap.put("supplayPrivateFactory", chainVos.getSupplayPrivateFactory());
            chainMap.put("supplayHaveVat", chainVos.getSupplayHaveVat());
            chainMap.put("supplyIor", chainVos.getSupplyIor());
            chainMap.put("supplyPrivateWearhouse", chainVos.getSupplyPrivateWearhouse());
            chainMap.put("supplyCrossEbay", chainVos.getSupplyCrossEbay());
            chainMap.put("supplayWearhouserAddress", chainVos.getSupplayWearhouserAddress());
            map.put("supplyChain", chainMap);
        }
        
        //海外仓国家
        List<Map<String, Object>> countryMaps = new ArrayList<Map<String, Object>>();
        List<SupplyCountryTepVo> countryList = vo.getSupplyCountryTepList();
        if(countryList!=null&&countryList.size()>0){
            for (SupplyCountryTepVo country : countryList) {
                Map<String, Object> countryMap = new HashMap<String, Object>();
                countryMap.put("name", country.getName());
                countryMap.put("code", country.getCode());
                countryMaps.add(countryMap);
            }
        }
        map.put("CountryTep", countryMaps);
        
        //旺季月份
        List<Map<String, Object>> peakMaps = new ArrayList<Map<String, Object>>();
        List<SupplyPeakmonthTepVo> peakList = vo.getSupplyPeakmonthTepList();
        if(peakList!=null&&peakList.size()>0){
            for (SupplyPeakmonthTepVo peak : peakList) {
                Map<String, Object> peakMap = new HashMap<String, Object>();
                peakMap.put("name", peak.getName());
                peakMap.put("code", peak.getCode());
                peakMaps.add(peakMap);
            } 
        }
        map.put("supplyPeakmonth", peakMaps);
        
        //淡季月份
        List<Map<String, Object>> slackMaps = new ArrayList<Map<String, Object>>();
        List<SupplySlackmonthTepVo> slackList = vo.getSupplySlackmonthTepList();
        if(slackList!=null&&slackList.size()>0){
            for (SupplySlackmonthTepVo slack : slackList) {
                Map<String, Object> slackMap = new HashMap<String, Object>();
                slackMap.put("name", slack.getName());
                slackMap.put("code", slack.getCode());
                slackMaps.add(slackMap);
            }
        }
        map.put("supplySlackmonth", slackMaps);
        
        //商品分类
        List<Map<String, Object>> merchandiseMaps = new ArrayList<Map<String, Object>>();
        List<MerchandiseCategoriesTepVo> merchandiseList = vo.getMerchandiseCategoriesTepList();
        if(merchandiseList != null && merchandiseList.size() > 0){
        	for (MerchandiseCategoriesTepVo merchandise : merchandiseList) {
        		Map<String, Object> merchandiseMap = new HashMap<String, Object>();
        		merchandiseMap.put("name", merchandise.getName());
        		merchandiseMap.put("code", merchandise.getCode());
        		merchandiseMaps.add(merchandiseMap);
			}
        }
        map.put("merchandiseCategories", merchandiseMaps);
        
		return map;
	}
	

    /**
	 * 身份证唯一性校验
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value="/checkIdentityCardUnique")
	public String checkIdentityCardUnique(@ModelAttribute RequestMsg requestMsg,@ModelAttribute ResponseMsg responseMsg){
		CheckIdentityCommand command = JSON.parseObject(requestMsg.getData().toString(), CheckIdentityCommand.class);
		command.setCtx(CommandContext.getContext());
		boolean flag = registerTemporaryService.checkIdentityCardUnique(command);
		Map<String, Boolean> data = new HashMap<String, Boolean>();
        data.put("flag", flag);
        responseMsg.setData(data);
        return SUCCESS;          
        }
	
	/**
	 * 客户名称唯一性校验
	 * @param requestMsg
	 * @param responseMsg
	 * @return
	 */
	@RequestMapping(value="/checkCustomerNameUnique")
	public String checkCustomerNameUnique(@ModelAttribute RequestMsg requestMsg,@ModelAttribute ResponseMsg responseMsg){
		CheckCustomerNameCommand command = JSON.parseObject(requestMsg.getData().toString(), CheckCustomerNameCommand.class);
		command.setCtx(CommandContext.getContext());
		boolean flag = registerTemporaryService.checkCustomerNameUnique(command);
		Map<String, Boolean> data = new HashMap<String, Boolean>();
        data.put("flag", flag);
        responseMsg.setData(data);
        return SUCCESS;          
        }
	
	
	/**
     * 查询推广链接信息
     * @param requestMsg
     * @param responseMsg
     * @return String
     * */
    @RequestMapping(value="/queryPromoteUrl")
    public String queryPromoteUrlByCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        QueryActivityTypeCommand command = JSON.parseObject(requestMsg.getData().toString(), QueryActivityTypeCommand.class);
        PromoteUrlVo vo = promoteService.queryPromoteUrlByCode(command);     
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("promoteVo", vo);
        responseMsg.setData(map);        
        return SUCCESS;
    }
    
    
    /**
     * 活动页面增加潜在客户
     * @param requestMsg
     * @param responseMsg
     * @return String
     * */
    @RequestMapping(value="/addPotentialCustomer")
    public String addPotentialCustomer(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        AddPotentialCustomerCommand command = JSON.parseObject(requestMsg.getData().toString(), AddPotentialCustomerCommand.class);
        registerTemporaryService.addPotentialCustomer(command);       
        return SUCCESS;
    }
    
    /**
     * 统计推广链接点击率
     * @param requestMsg
     * @param responseMsg
     * @return String
     * */
    @RequestMapping(value="/updateClickAccout")
    public String updateClickAccout(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        UpdatePromoteUrlCommand command = JSON.parseObject(requestMsg.getData().toString(), UpdatePromoteUrlCommand.class);
        promoteService.updateClickAccout(command);       
        return SUCCESS;
    }
    
    /**
     * 统计推广链接点击率
     * @param requestMsg
     * @param responseMsg
     * @return String
     * */
    @SuppressWarnings("unchecked")
	@RequestMapping(value="/existsRecommendUser")
    public String existsRecommendUser(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        GetByKeyCommand<String> command = JSON.parseObject(requestMsg.getData().toString(), GetByKeyCommand.class);
        boolean flag = false;
        UserVO userVO =  umsUserService.queryByUsername(command);  
        if(userVO!=null){
            flag = true;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("flag", flag);
        responseMsg.setData(map); 
        return SUCCESS;
    }

	/**
	 * 变更客户主体
	 *
	 * @param requestMsg
	 * @param responseMsg
	 * @return String
	 */
	@RequestMapping(value = "/modifyCustomerBody")
	private String customerChangeBody(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
		CustomerChangeBodyCommand command = JSON.parseObject(requestMsg.getData().toString(), CustomerChangeBodyCommand.class);
		command.setCtx(CommandContext.getContext());
		registerTemporaryService.customerChangeBody(command);
		return SUCCESS;
	}
    
}
